package com.xique.door.biz.service.impl;

import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.datascope.annotation.NeedSetFieldValue;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.request.AccessDevice.HouseSearchDeviceRequest;
import com.xique.door.bean.request.buildHouse.BuildHouseBandUserRequest;
import com.xique.door.bean.request.buildHouse.BuildHouseDeleteUserRequest;
import com.xique.door.bean.request.user.UserAddHouseRequest;
import com.xique.door.bean.request.user.UserSelectRequest;
import com.xique.door.bean.search.UserDeviceSearch;
import com.xique.door.bean.validation.HouseUserValidation;
import com.xique.door.bean.vo.user.UserHouseVo;
import com.xique.door.biz.service.IBuildHouseUserBizService;
import com.xique.door.biz.service.IDeviceBizService;
import com.xique.door.command.IDeviceUserCommandService;
import com.xique.door.device.freeview.constant.CommandStatus;
import com.xique.door.mapper.BuildHouseMapper;
import com.xique.door.mapper.BuildHouseUserMapper;
import com.xique.door.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: caogq
 * @Date: 2022/1/19 14:45
 * @Description:
 */
@Service
public class BuildHouseUserBizService implements IBuildHouseUserBizService {
    @Autowired
    private BuildHouseUserMapper buildHouseUserMapper;

    @Autowired
    private BuildHouseMapper buildHouseMapper;

    @Autowired
    private IBuildBuildingService buildBuildingService;

    @Autowired
    private IBuildHouseUserService houseUserService;


    @Autowired
    private IBuildHouseService buildHouseService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBuildAreaService buildAreaService;

    @Autowired
    private IUserDeviceService userDeviceService;
    @Autowired
    private IDeviceUserCommandService deviceUserCommandService;

    @Autowired
    private IDeviceBizService deviceBizService;

    @Autowired
    private IAccessDeviceService accessDeviceService;

    @Autowired
    private HouseUserValidation houseUserValidation;

    @Autowired
    private IBuildingDeviceService buildingDeviceService;

    @Override
    public AjaxResult addHouseUser(BuildHouseBandUserRequest request) {
        //step1:add house and user
        int i = this.addBuildHouseUserBaseInfo(request);
        if (i < 1) {
            return AjaxResult.error("用户绑定房屋时发生错误!");
        }
        //step2:add device and user
//        List<AccessDevice> accessDevices = deviceBizService.selectDeviceByHouseIds(request.getHouseIds());
        HouseSearchDeviceRequest houseSearchDeviceRequest = new HouseSearchDeviceRequest();
        houseSearchDeviceRequest.setHouseIds(request.getHouseIds());
        List<AccessDevice> accessDevices = accessDeviceService.selectAccessDevicesByHouseIds(houseSearchDeviceRequest);
        User user = request.getUser();
        List<UserDevice> userDevices = new ArrayList<>();
        for (AccessDevice accessDevice : accessDevices) {
            UserDevice userDevice = new UserDevice();
            userDevice.setParkId(request.getParkId());
            userDevice.setModel(accessDevice.getModel());
            userDevice.setUserId(user.getId());
            userDevice.setDeviceId(accessDevice.getId());
            userDevice.setDevSn(accessDevice.getDevSn());
            if (StringUtils.isEmpty(accessDevice.getOnlineStatus()) || "offline".equals(accessDevice.getOnlineStatus())) {
                userDevice.setStatus(CommandStatus.PENDING);
            } else {
                if (StringUtils.isNotEmpty(user.getFaceUrl())) {
                    userDevice.setStatus(CommandStatus.SEND);
                } else {
                    userDevice.setStatus(CommandStatus.NOFACE);
                }
            }
            userDevice.setCustomId(user.getCustomId());
            userDevice.setModel(accessDevice.getModel());
            userDevice.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            userDevices.add(userDevice);
        }
        userDeviceService.batchInsertUserDevice(userDevices);
        //step3: command
        deviceUserCommandService.downDevicesUsers(accessDevices, Collections.singletonList(user));
        return AjaxResult.success();
    }

    @Override
    public AjaxResult userAddHouses(User user, UserAddHouseRequest houseRequest) {
        BuildHouse house = buildHouseMapper.selectBuildHouseById(houseRequest.getHouseId());
        BuildHouseUser buildHouseUser = new BuildHouseUser();
        buildHouseUser.setUserId(user.getId());
        buildHouseUser.setHouseId(house.getId());
        buildHouseUser.setHouseName(house.getHouseName());
        buildHouseUser.setUserName(user.getUserName());
        buildHouseUser.setRelation(houseRequest.getRelation());
        buildHouseUser.setIdentityType(houseRequest.getIdentityType());
        buildHouseUser.setBuildingId(house.getBuildingId());
        buildHouseUser.setBuildingName(house.getBuildingName());
        buildHouseUserMapper.insertBuildHouseUser(buildHouseUser);
        HouseSearchDeviceRequest houseSearchDeviceRequest = new HouseSearchDeviceRequest();
        houseSearchDeviceRequest.setHouseId(houseRequest.getHouseId());
        List<AccessDevice> accessDevices = accessDeviceService.selectAccessDevicesByHouseIds(houseSearchDeviceRequest);
        List<UserDevice> userDevices = new ArrayList<>();
        for (AccessDevice accessDevice : accessDevices) {
            UserDevice userDevice = new UserDevice();
            userDevice.setParkId(user.getParkId());
            userDevice.setModel(accessDevice.getModel());
            userDevice.setUserId(user.getId());
            userDevice.setDeviceId(accessDevice.getId());
            userDevice.setDevSn(accessDevice.getDevSn());
            if (StringUtils.isEmpty(accessDevice.getOnlineStatus()) || "offline".equals(accessDevice.getOnlineStatus())) {
                userDevice.setStatus(CommandStatus.PENDING);
            } else {
                if (StringUtils.isNotEmpty(user.getFaceUrl())) {
                    userDevice.setStatus(CommandStatus.SEND);
                } else {
                    userDevice.setStatus(CommandStatus.NOFACE);
                }
            }
            userDevice.setCustomId(user.getCustomId());
            userDevice.setModel(accessDevice.getModel());
            userDevice.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
//            userDeviceService.insertUserDevice(userDevice);
            userDevices.add(userDevice);
        }
        int i = userDeviceService.batchInsertUserDevice(userDevices);
        //step3: 下发
        if (StringUtils.isNotEmpty(user.getFaceUrl())) {
            //照片不为空才下发
            deviceUserCommandService.downDevicesUsers(accessDevices, Collections.singletonList(user));
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteHouseUser(BuildHouseDeleteUserRequest request) {
        //4、删除用户房屋中间表
        BuildHouseUser buildHouseUser = new BuildHouseUser();
        buildHouseUser.setHouseId(request.getHouseId());
        buildHouseUser.setUserId(request.getUserId());
        List<BuildHouseUser> buildHouseUsers = buildHouseUserMapper.selectBuildHouseUserList(buildHouseUser);
        buildHouseUserMapper.deleteBuildHouseUserById(buildHouseUsers.get(0).getId());

        //TODO 删除用户和设备中间表
        return AjaxResult.success();
    }

    @Override
    public User selectHouseOwner(Long houseId) {
        BuildHouseUser search = new BuildHouseUser();
        search.setHouseId(houseId);
        search.setIdentityType("0");
        List<BuildHouseUser> houseOwner = houseUserService.selectBuildHouseUserList(search);
        if (houseOwner.isEmpty()) {
            return null;
        }
        User user = userService.selectUserById(houseOwner.get(0).getUserId());
        return user;
    }


    public int addBuildHouseUserBaseInfo(BuildHouseBandUserRequest request) {
        //1、新增用户房屋中间表
        User user = request.getUser();
        BuildHouse house = buildHouseMapper.selectBuildHouseById(request.getHouseId());
        BuildHouseUser buildHouseUser = new BuildHouseUser();
        buildHouseUser.setUserId(user.getId());
        buildHouseUser.setHouseId(request.getHouseId());
        buildHouseUser.setHouseName(house.getHouseName());
        buildHouseUser.setUserName(user.getUserName());
        buildHouseUser.setRelation(request.getRelation());
        buildHouseUser.setLiveWay(request.getLiveWay());
        buildHouseUser.setCheckInDate(request.getCheckInDate());
        buildHouseUser.setIdentityType(request.getIdentityType());
        buildHouseUser.setBuildingId(house.getBuildingId());
        buildHouseUser.setBuildingName(house.getBuildingName());
        return buildHouseUserMapper.insertBuildHouseUser(buildHouseUser);

    }

    /**
     * @description: 查询用户的房屋信息
     * @author caogq
     * @date: 2022/1/27 10:19
     * @Param
     */
    @Override
    public List<UserHouseVo> selectBindHouseList(Long userId) {
        BuildHouseUser buildHouseUser = new BuildHouseUser();
        buildHouseUser.setUserId(userId);
        List<BuildHouseUser> buildHouseUsers = houseUserService.selectBuildHouseUserList(buildHouseUser);
        List<UserHouseVo> userHouseVos = new ArrayList<>();
        for (BuildHouseUser houseUser : buildHouseUsers) {
            UserHouseVo userHouseVo = OrikaUtil.convert(houseUser, UserHouseVo.class);
            BuildHouse house = buildHouseService.selectBuildHouseById(houseUser.getHouseId());
            userHouseVo.setHouseCode(house.getHouseCode());
            BuildBuilding buildBuilding = buildBuildingService.selectBuildBuildingById(house.getBuildingId());
            userHouseVo.setBuildingName(house.getBuildingName());
            userHouseVo.setAreaName(buildAreaService.selectBuildAreaById(buildBuilding.getAreaId()).getAreaName());
            userHouseVos.add(userHouseVo);
        }
        return userHouseVos;
    }

    /**
     * @description: 查询未绑定的房屋信息
     * @author caogq
     * @date: 2022/1/27 10:19
     */
    @Override
    @NeedSetFieldValue
    public List<UserHouseVo> convertUnBindHouseList(List<BuildHouse> buildHouses) {
//        List<BuildHouse> buildHouses = houseUserService.selectUnBindHouseList(request);
        List<UserHouseVo> userHouseVos = new ArrayList<>();
        for (BuildHouse buildHouse : buildHouses) {
            UserHouseVo userHouseVo = new UserHouseVo();
            userHouseVo.setHouseId(buildHouse.getId());
            userHouseVo.setHouseCode(buildHouse.getHouseCode());
            userHouseVo.setBuildingName(buildHouse.getBuildingName());
            userHouseVo.setAreaId(buildHouse.getAreaId());
            BuildArea area= buildAreaService.selectBuildAreaById(buildHouse.getAreaId());
            userHouseVo.setAreaName(area.getAreaName());
            userHouseVos.add(userHouseVo);
        }
        return userHouseVos;
    }

    @Override
    public List<BuildHouse> selectUnBindHouseList(UserSelectRequest request) {
        return houseUserService.selectUnBindHouseList(request);
    }


    /**
     * @description: 绑定房屋
     * @author caogq
     * @date: 2022/1/27 10:19
     * @Param
     */
    @Override
    public AjaxResult bindHouse(BuildHouseUser buildHouseUser) {
        AjaxResult result = houseUserValidation.userBandHouseValidation(buildHouseUser);
        if (AjaxResult.isError(result)) {
            return result;
        }
        //1、新增房屋用户
        User user = userService.selectUserById(buildHouseUser.getUserId());
        houseUserService.insertBuildHouseUser(buildHouseUser);
        //2、新增用户设备
        UserDevice userDeviceSearch = new UserDevice();
        userDeviceSearch.setUserId(buildHouseUser.getUserId());
        List<UserDevice> oldUserDevices = userDeviceService.selectUserDeviceList(userDeviceSearch);
        List<Long> oldDeviceIds = oldUserDevices.stream().map(UserDevice::getDeviceId).collect(Collectors.toList());
        List<AccessDevice> oldAccessDevices = accessDeviceService.selectAccessDeviceByIds(oldDeviceIds);

        HouseSearchDeviceRequest houseSearchDeviceRequest = new HouseSearchDeviceRequest();
        houseSearchDeviceRequest.setHouseId(buildHouseUser.getHouseId());
        List<AccessDevice> newAccessDevices = accessDeviceService.selectAccessDevicesByHouseIds(houseSearchDeviceRequest);
        List<Long> newDeviceIds = newAccessDevices.stream().map(AccessDevice::getId).collect(Collectors.toList());

        //3、下发逻辑：新增房屋所对应的设备需要全部下发（梯控数据会有变化），如果新房屋对应的设备，之前没有和用户绑定过，需要新增中间表，反之更新中间表
        List<AccessDevice> addDevices = newAccessDevices.stream().filter(e -> !oldDeviceIds.contains(e.getId())).collect(Collectors.toList());
        List<UserDevice> updateDevices = oldUserDevices.stream().filter(e -> newDeviceIds.contains(e.getDeviceId())).collect(Collectors.toList());
        List<AccessDevice> needCommandDevcies = new ArrayList<>();
        if (addDevices.isEmpty() && updateDevices.isEmpty()) {
            return AjaxResult.success();
        }
        List<UserDevice> addUserDevices = new ArrayList<>();
        for (AccessDevice accessDevice : addDevices) {
            UserDevice userDevice = new UserDevice();
            userDevice.setParkId(SecurityUtils.getParkId());
            userDevice.setModel(accessDevice.getModel());
            userDevice.setUserId(buildHouseUser.getUserId());
            userDevice.setDeviceId(accessDevice.getId());
            userDevice.setDevSn(accessDevice.getDevSn());
            if (StringUtils.isEmpty(accessDevice.getOnlineStatus()) || "offline".equals(accessDevice.getOnlineStatus())) {
                userDevice.setStatus(CommandStatus.PENDING);
            } else {
                if (StringUtils.isNotEmpty(user.getFaceUrl())) {
                    userDevice.setStatus(CommandStatus.SEND);
                } else {
                    userDevice.setStatus(CommandStatus.NOFACE);
                }
            }
            userDevice.setCustomId(user.getCustomId());
            userDevice.setModel(accessDevice.getModel());
            userDevice.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            addUserDevices.add(userDevice);
            needCommandDevcies.add(accessDevice);
        }
        if (!addUserDevices.isEmpty()) {
            userDeviceService.batchInsertUserDevice(addUserDevices);
        }
        List<UserDevice> updateUserDevices = new ArrayList<>();
        for (UserDevice userDevice : updateDevices) {
            AccessDevice accessDevice = oldAccessDevices.stream().filter(e -> e.getId().equals(userDevice.getDeviceId())).findAny().orElse(null);
            needCommandDevcies.add(accessDevice);
            if (accessDevice != null && (StringUtils.isEmpty(accessDevice.getOnlineStatus()) || "offline".equals(accessDevice.getOnlineStatus()))) {
                userDevice.setStatus(CommandStatus.PENDING);
            } else {
                if (StringUtils.isNotEmpty(user.getFaceUrl())) {
                    userDevice.setStatus(CommandStatus.SEND);
                } else {
                    userDevice.setStatus(CommandStatus.NOFACE);
                }
            }
            userDevice.setUpdateTime(new Date());
            updateUserDevices.add(userDevice);
        }
        if (!updateUserDevices.isEmpty()) {
            userDeviceService.batchUpdateUserDevice(updateUserDevices);
        }

        if (StringUtils.isNotEmpty(user.getFaceUrl())) {
            //3、重新下发用户到设备()
            return deviceUserCommandService.downDevicesUsers(needCommandDevcies, Collections.singletonList(user));
        }
        return AjaxResult.success();
    }

    /**
     * @param buildHouseUser
     * @description: 解绑房屋
     * @author caogq
     * @date: 2022/1/27 10:19
     * @Param
     */
    @Override
    public AjaxResult unBindHouse(BuildHouseUser buildHouseUser) {
        User user = userService.selectUserById(buildHouseUser.getUserId());

        //1、查出原先的用户设备表
        UserDevice userDeviceSearch = new UserDevice();
        userDeviceSearch.setUserId(buildHouseUser.getUserId());
        List<UserDevice> oldUserDevices = userDeviceService.selectUserDeviceList(userDeviceSearch);
        List<Long> oldDeviceIds = oldUserDevices.stream().map(UserDevice::getDeviceId).collect(Collectors.toList());
        List<AccessDevice> oldAccessDevices = accessDeviceService.selectAccessDeviceByIds(oldDeviceIds);

        //2、删除用户和房屋中间表
        List<BuildHouseUser> buildHouseUsers = houseUserService.selectBuildHouseUserList(buildHouseUser);
        int i = houseUserService.deleteBuildHouseUserById(buildHouseUsers.get(0).getId());

        //4、删除用户设备中间表逻辑：1、查询原有的用户设备中间表 2、查询解绑房屋所在的设备 3、查询未解绑房屋所在设备 4、查询2设备集合中不含有的3设备集合，这些设备需要删除
        HouseSearchDeviceRequest houseSearchDeviceRequest = new HouseSearchDeviceRequest();
        houseSearchDeviceRequest.setHouseId(buildHouseUser.getHouseId());
        List<AccessDevice> newHouseDevices = accessDeviceService.selectAccessDevicesByHouseIds(houseSearchDeviceRequest);

        List<AccessDevice> needDeleteDevices = newHouseDevices.stream().filter(e -> !oldDeviceIds.contains(e.getId())).collect(Collectors.toList());
        List<AccessDevice> updateDevices = newHouseDevices.stream().filter(e -> oldDeviceIds.contains(e.getId())).collect(Collectors.toList());
//        List<UserDevice> updateDevices = oldUserDevices.stream().filter(e -> newHouseDevices.contains(e.getDeviceId())).collect(Collectors.toList());


        List<AccessDevice> needCommandDevcies = new ArrayList<>();

        deviceUserCommandService.deleteDevicesUsers(needDeleteDevices, Collections.singletonList(user));
        BuildHouse buildHouse = buildHouseService.selectBuildHouseById(buildHouseUser.getHouseId());
        if (StringUtils.isNotEmpty(user.getFaceUrl()) && !updateDevices.isEmpty()) {
            for (AccessDevice updateDevice : updateDevices) {
                AccessDevice accessDevice = oldAccessDevices.stream().filter(e -> e.getId().equals(updateDevice.getId())).findAny().orElse(null);
                //找出当前楼栋下的其他梯控机，如果存在需要修改梯控信息重新下发
                if ("cell".equals(accessDevice.getAccessType()) && accessDevice.getForeignId().equals(buildHouse.getBuildingId())) {
                    needCommandDevcies.add(accessDevice);
                }
            }
            //3、更新梯控
            return deviceUserCommandService.downDevicesUsers(needCommandDevcies, Collections.singletonList(user));
        }
        //5、重新下发用户到设备
        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }


    @Override
    public AjaxResult unBindHouseV2(BuildHouseUser buildHouseUser) {
        //-------------------------------------------用户单房屋---------------------------------------
        User user = userService.selectUserById(buildHouseUser.getUserId());
        //1、查询用户所有房屋所对应的设备
        BuildHouseUser allHouseUserSearch = new BuildHouseUser();
        allHouseUserSearch.setUserId(buildHouseUser.getUserId());
        List<BuildHouseUser> allHouseUsers = houseUserService.selectBuildHouseUserList(allHouseUserSearch);

        //2、查询此次解绑房屋对应的设备
        HouseSearchDeviceRequest houseSearchDeviceRequest = new HouseSearchDeviceRequest();
        houseSearchDeviceRequest.setHouseId(buildHouseUser.getHouseId());
        List<AccessDevice> unBindHouseDevices = accessDeviceService.selectAccessDevicesByHouseIds(houseSearchDeviceRequest);

        if (!allHouseUsers.isEmpty() && allHouseUsers.size() == 1  ) {
            //用户只有一个房屋，删除中间表，删除该房屋绑定的设备中的人员。
            int i = houseUserService.deleteBuildHouseUserById(allHouseUsers.get(0).getId());
            if (!unBindHouseDevices.isEmpty()){
                this.updateUserDevice(unBindHouseDevices,user);
                return deviceUserCommandService.deleteDevicesUsers(unBindHouseDevices, Collections.singletonList(user));
            }
        }

        //-------------------------------------------用户多房屋---------------------------------------
        //1、查询其他房屋所绑定的设备
        List<Long> otherHouseIds = allHouseUsers.stream()
                .filter(e -> !e.getHouseId().equals(buildHouseUser.getHouseId()))
                .map(BuildHouseUser::getHouseId)
                .collect(Collectors.toList());
        HouseSearchDeviceRequest otherHouseRequest = new HouseSearchDeviceRequest();
        otherHouseRequest.setHouseIds(otherHouseIds);
        List<AccessDevice> otherHouseDevices = accessDeviceService.selectAccessDevicesByHouseIds(otherHouseRequest);

        //2、删除解绑的房屋和用户的中间表数据
        List<BuildHouseUser> needDeleteHouseUsers = houseUserService.selectBuildHouseUserList(buildHouseUser);
        if (needDeleteHouseUsers.isEmpty() || needDeleteHouseUsers.size() > 1) {
            return AjaxResult.error();
        }
        int i = houseUserService.deleteBuildHouseUserById(needDeleteHouseUsers.get(0).getId());
        //3、找出需要删除下发的设备.删除下发
        List<AccessDevice> needDeleteDevices = unBindHouseDevices.stream().filter(e -> !otherHouseDevices.contains(e)).collect(Collectors.toList());
        if (!needDeleteDevices.isEmpty()){
            this.updateUserDevice(needDeleteDevices,user);
            deviceUserCommandService.deleteDevicesUsers(needDeleteDevices, Collections.singletonList(user));
        }
        //4、找出需要更新梯控信息下发的设备（查询同一个楼栋下的梯控机）,更新梯控下发
        BuildHouse buildHouse = buildHouseService.selectBuildHouseById(buildHouseUser.getHouseId());
        BuildingDevice buildingDevice = new BuildingDevice();
        buildingDevice.setBuildingId(buildHouse.getBuildingId());
        List<BuildingDevice> buildingDevices = buildingDeviceService.selectBuildingDeviceList(buildingDevice);
        List<Long> buildingDeviceIds = buildingDevices.stream().map(BuildingDevice::getDeviceId).collect(Collectors.toList());

        List<AccessDevice> needUpdateDevices = otherHouseDevices.stream()
                .filter(e -> e.getAccessType().equals("elevator") && buildingDeviceIds.contains(e.getId()))
                .collect(Collectors.toList());
        if (!needUpdateDevices.isEmpty() && StringUtils.isNotEmpty(user.getFaceUrl())){
            this.updateUserDevice(needUpdateDevices,user);
            return deviceUserCommandService.downDevicesUsers(needUpdateDevices, Collections.singletonList(user));
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult bindHouseV2(BuildHouseUser buildHouseUser) {

        BuildHouseV1 houseV1 = buildHouseService.getById(buildHouseUser.getHouseId());
        if (!StringUtils.isNull(houseV1) && !StringUtils.isNull(houseV1.getMaxInNumber())) {
            int count = houseUserService.checkHouseUserCount(buildHouseUser.getHouseId());
            if (count >= houseV1.getMaxInNumber()) {
                return AjaxResult.error("已超出该房屋最大可入住数量，无法绑定");
            }
        }
        //0、校验
        AjaxResult result = houseUserValidation.userBandHouseValidation(buildHouseUser);
        if (AjaxResult.isError(result)) {
            return result;
        }
        User user = userService.selectUserById(buildHouseUser.getUserId());

        //----------------------------------用户未添加过房屋-----------------------------------

        //1、查询此次绑定房屋对应的设备
        HouseSearchDeviceRequest houseSearchDeviceRequest = new HouseSearchDeviceRequest();
        houseSearchDeviceRequest.setHouseId(buildHouseUser.getHouseId());
        List<AccessDevice> bindHouseDevices = accessDeviceService.selectAccessDevicesByHouseIds(houseSearchDeviceRequest);


        //2、找出原有的房屋用户中间表数据
        BuildHouseUser allHouseUserSearch = new BuildHouseUser();
        allHouseUserSearch.setUserId(buildHouseUser.getUserId());
        List<BuildHouseUser> allHouseUsers = houseUserService.selectBuildHouseUserList(allHouseUserSearch);
        houseUserService.insertBuildHouseUser(buildHouseUser);
        if (allHouseUsers.isEmpty() && !bindHouseDevices.isEmpty()) {
            //用户没绑定过房屋
            this.addUserDevice(bindHouseDevices, user);
            return deviceUserCommandService.downDevicesUsers(bindHouseDevices, Collections.singletonList(user));
        }

        //----------------------------------用户之前已经有过房屋-----------------------------------
        //1、查询其他房屋所绑定的设备
        List<Long> otherHouseIds = allHouseUsers.stream()
                .filter(e -> !e.getHouseId().equals(buildHouseUser.getHouseId()))
                .map(BuildHouseUser::getHouseId)
                .collect(Collectors.toList());
        HouseSearchDeviceRequest otherHouseRequest = new HouseSearchDeviceRequest();
        otherHouseRequest.setHouseIds(otherHouseIds);
        List<AccessDevice> otherHouseDevices = accessDeviceService.selectAccessDevicesByHouseIds(otherHouseRequest);

        //5、过滤出需要新增的设备，下发人员信息
        List<AccessDevice> needAddDevices = bindHouseDevices.stream().filter(e -> !otherHouseDevices.contains(e)).collect(Collectors.toList());
        if (!needAddDevices.isEmpty()){
            this.addUserDevice(needAddDevices, user);
        }
        //6、找出需要更新梯控信息下发的设备（查询同一个楼栋下的梯控机）,更新梯控下发
        BuildHouse buildHouse = buildHouseService.selectBuildHouseById(buildHouseUser.getHouseId());
        BuildingDevice buildingDevice = new BuildingDevice();
        buildingDevice.setBuildingId(buildHouse.getBuildingId());
        List<BuildingDevice> buildingDevices = buildingDeviceService.selectBuildingDeviceList(buildingDevice);
        List<Long> buildingDeviceIds = buildingDevices.stream().map(BuildingDevice::getDeviceId).collect(Collectors.toList());

        List<AccessDevice> needUpdateDevices = otherHouseDevices.stream()
                .filter(e -> e.getAccessType().equals("elevator") && buildingDeviceIds.contains(e.getId()))
                .collect(Collectors.toList());
        if (!needUpdateDevices.isEmpty()){
            this.updateUserDevice(needUpdateDevices, user);
        }
        //需要下发的设备= 需要新增+修改的设备
        needAddDevices.addAll(needUpdateDevices);

        if (StringUtils.isNotEmpty(user.getFaceUrl())) {
            return deviceUserCommandService.downDevicesUsers(needAddDevices, Collections.singletonList(user));
        }

        return AjaxResult.success();
    }

    public int addUserDevice(List<AccessDevice> addDevices, User user) {
        List<UserDevice> addUserDevices = new ArrayList<>();
        for (AccessDevice accessDevice : addDevices) {
            UserDevice userDevice = new UserDevice();
            userDevice.setParkId(SecurityUtils.getParkId());
            userDevice.setModel(accessDevice.getModel());
            userDevice.setUserId(user.getId());
            userDevice.setDeviceId(accessDevice.getId());
            userDevice.setDevSn(accessDevice.getDevSn());
            if (StringUtils.isEmpty(accessDevice.getOnlineStatus()) || "offline".equals(accessDevice.getOnlineStatus())) {
                userDevice.setStatus(CommandStatus.PENDING);
            } else {
                if (StringUtils.isNotEmpty(user.getFaceUrl())) {
                    userDevice.setStatus(CommandStatus.SEND);
                } else {
                    userDevice.setStatus(CommandStatus.NOFACE);
                }
            }
            userDevice.setCustomId(user.getCustomId());
            userDevice.setModel(accessDevice.getModel());
            userDevice.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            addUserDevices.add(userDevice);
        }
        if (!addUserDevices.isEmpty()) {
            userDeviceService.batchInsertUserDevice(addUserDevices);
        }
        return 1;
    }

    public int updateUserDevice(List<AccessDevice> accessDevices, User user) {
        UserDeviceSearch userDeviceSearch = new UserDeviceSearch();
        userDeviceSearch.setUserId(user.getId());
        userDeviceSearch.setDeviceIds(accessDevices.stream().map(AccessDevice::getId).collect(Collectors.toList()));
        List<UserDevice> updateDevices = userDeviceService.selectUserDeviceListBySearch(userDeviceSearch);
        if (updateDevices.isEmpty()) {
            return 1;
        }
        for (UserDevice userDevice : updateDevices) {
            AccessDevice accessDevice = accessDevices.stream().filter(e -> e.getId().equals(userDevice.getDeviceId())).findAny().orElse(null);
            if (accessDevice != null && (StringUtils.isEmpty(accessDevice.getOnlineStatus()) || "offline".equals(accessDevice.getOnlineStatus()))) {
                userDevice.setStatus(CommandStatus.PENDING);
            } else {
                if (StringUtils.isNotEmpty(user.getFaceUrl())) {
                    userDevice.setStatus(CommandStatus.SEND);
                } else {
                    userDevice.setStatus(CommandStatus.NOFACE);
                }
            }
            userDevice.setUpdateTime(new Date());
        }
        return userDeviceService.batchUpdateUserDevice(updateDevices);
    }

}
